package com.zhenyi.liuxue.interceptor;

import com.cjw.model.DBMap;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.liuxue.common.model.LxUser;
import com.utils.AuthUtils;

public class AppAuthInterceptor implements Interceptor {

	private void renderLogin(Controller controller) {
		// http://localhost:9090/lx/mini/activity/detail?id=7
		String ref = getRequestUrl(controller);
		controller.setCookie("ref", ref, -1);
		controller.redirect("/lx/mini/user/signIn");
		// String before = getRequestUrl(controller);
		// controller.redirect("/jh/app?state=" + URLUtil.encode(before));
	}

	private String getRequestUrl(Controller controller) {
		String url = controller.getRequest().getRequestURL().toString();
		String queryurl = controller.getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		try {
			String uid = AuthUtils.getTokenUid(controller);
			if (StrKit.notBlank(uid)) {
				LxUser user = LxUser.dao.findById(Long.parseLong(uid));
				if (user == null) {
					renderLogin(controller);
					return;
				}
				inv.invoke();
			} else {
				renderLogin(controller);
				return;
			}
		} catch (NumberFormatException e) {
			renderLogin(controller);
		} catch (Exception e) {
			e.printStackTrace();
			DBMap map = new DBMap();
			map.put("status", 500);
			map.put("msg", "出错");
			controller.renderJson(map);
		}
	}

}
